package com.zy.rpc.common.Serializer.impl;

import com.google.protobuf.InvalidProtocolBufferException;
import com.zy.rpc.common.Serializer.Serializer;
import com.zy.rpc.common.ask.RpcRequest;
import com.zy.rpc.common.ask.RpcResponse;
import com.zy.rpc.common.protobuf.RequestProto;
import com.zy.rpc.common.protobuf.ResponseProto;


public class ProtobufSerializer implements Serializer {


    @Override
    public <T> T deserialize(Class<T> clazz, byte[] bytes) {
        System.out.println(clazz.getName());
        try {
            if(clazz.equals(RpcResponse.class)){
                System.out.println(3);
                return clazz.cast(ResponseProto.RpcResponse.parseFrom(bytes));
            } else if (clazz.equals(RpcRequest.class)) {
                System.out.println(4);
                return clazz.cast(RequestProto.RpcRequest.parseFrom(bytes));
            }
        } catch (InvalidProtocolBufferException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    @Override
    public <T> byte[] serialize(T object) {
        if (object instanceof RpcResponse){
            System.out.println(1);
            ResponseProto.RpcResponse redemo=(ResponseProto.RpcResponse) object;
            return  redemo.toByteArray();
        } else if (object instanceof  RpcRequest) {
            System.out.println(2);
            RequestProto.RpcRequest demo=(RequestProto.RpcRequest) object;

            byte[] bytes = demo.toByteArray();
            return bytes;
        }
        return null;
    }

//    @Override
//    public <T> byte[] serialize(T object) {
//        if (object instanceof RpcResponse){
//            System.out.println(1);
//            ResponseProto.RpcResponse redemo=(ResponseProto.RpcResponse) object;
//            return  redemo.toByteArray();
//        } else if (object instanceof  RpcRequest) {
//            System.out.println(2);
//
//            RpcRequest rpcRequest=(RpcRequest) object;
//
//            RequestProto.RpcRequest.Builder req=RequestProto.RpcRequest.newBuilder()
//                    .setParamsType(rpcRequest.getParamsType())
//            RequestProto.RpcRequest demo=(RequestProto.RpcRequest) object;
//
//            byte[] bytes = demo.toByteArray();
//            return bytes;
//        }
//        return null;
//    }


}
